<template>
  <div class="space-y-4">
    <!-- 标签 -->
    <label v-if="label" :for="inputId" class="block text-sm font-medium text-gray-700">
      {{ label }}
      <span v-if="required" class="text-red-500">*</span>
    </label>

    <!-- 地址输入框 -->
    <div class="relative">
      <input
        :id="inputId"
        v-model="addressInput"
        type="text"
        :placeholder="placeholder"
        :required="required"
        class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500"
        @input="handleAddressInput"
        @blur="handleAddressChange"
        @keyup.enter="handleAddressChange"
      />

      <!-- 清除按钮 -->
      <button
        v-if="addressInput"
        type="button"
        @click="clearAddress"
        class="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
      >
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
        </svg>
      </button>
    </div>

    <!-- 地址建议列表 -->
    <div v-if="showSuggestions && suggestions.length > 0" class="relative">
      <div class="absolute z-10 w-full bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto">
        <button
          v-for="(suggestion, index) in suggestions"
          :key="index"
          type="button"
          @click="selectSuggestion(suggestion)"
          class="w-full px-3 py-2 text-left hover:bg-gray-50 focus:bg-gray-50 focus:outline-none border-b border-gray-100 last:border-b-0"
        >
          <div class="text-sm text-gray-900">{{ suggestion.main }}</div>
          <div v-if="suggestion.secondary" class="text-xs text-gray-500">{{ suggestion.secondary }}</div>
        </button>
      </div>
    </div>

    <!-- 移除重复的地址显示区域 -->

    <!-- 帮助文本 -->
    <div v-if="helpText" class="text-xs text-gray-500">
      {{ helpText }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'

interface AddressSuggestion {
  main: string
  secondary?: string
  full: string
}

interface Props {
  modelValue?: string
  label?: string
  placeholder?: string
  required?: boolean
  helpText?: string
}

interface Emits {
  (e: 'update:modelValue', value: string): void
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请输入详细地址',
  helpText: '请输入完整的地址信息，包括街道、楼宇名称等'
})

const emit = defineEmits<Emits>()

// 生成唯一ID
const inputId = `address-picker-${Math.random().toString(36).substring(2, 11)}`

// 响应式数据
const addressInput = ref(props.modelValue || '')
const selectedAddress = ref(props.modelValue || '')
const showSuggestions = ref(false)
const suggestions = ref<AddressSuggestion[]>([])

// 香港常见地区建议
const hkLocationSuggestions = [
  { main: '中环', secondary: '中西区', full: '香港中环' },
  { main: '铜锣湾', secondary: '湾仔区', full: '香港铜锣湾' },
  { main: '尖沙咀', secondary: '油尖旺区', full: '九龙尖沙咀' },
  { main: '旺角', secondary: '油尖旺区', full: '九龙旺角' },
  { main: '深水埗', secondary: '深水埗区', full: '九龙深水埗' },
  { main: '观塘', secondary: '观塘区', full: '九龙观塘' },
  { main: '沙田', secondary: '沙田区', full: '新界沙田' },
  { main: '荃湾', secondary: '荃湾区', full: '新界荃湾' },
  { main: '屯门', secondary: '屯门区', full: '新界屯门' },
  { main: '元朗', secondary: '元朗区', full: '新界元朗' },
  { main: '大埔', secondary: '大埔区', full: '新界大埔' },
  { main: '上水', secondary: '北区', full: '新界上水' },
  { main: '西贡', secondary: '西贡区', full: '新界西贡' },
  { main: '将军澳', secondary: '西贡区', full: '新界将军澳' },
  { main: '东涌', secondary: '离岛区', full: '新界东涌' }
]

// 处理地址实时输入
const handleAddressInput = () => {
  const value = addressInput.value.trim()
  selectedAddress.value = value
  emit('update:modelValue', value)

  if (value) {
    generateSuggestions(value)
  } else {
    suggestions.value = []
    showSuggestions.value = false
  }
}

// 处理地址输入变化（失焦/回车时）
const handleAddressChange = () => {
  const value = addressInput.value.trim()

  if (value) {
    selectedAddress.value = value
    emit('update:modelValue', value)
    generateSuggestions(value)
  } else {
    clearAddress()
  }
}

// 生成地址建议
const generateSuggestions = (input: string) => {
  if (!input || input.length < 2) {
    suggestions.value = []
    showSuggestions.value = false
    return
  }

  const filtered = hkLocationSuggestions.filter(location =>
    location.main.includes(input) ||
    location.secondary?.includes(input) ||
    location.full.includes(input)
  )

  suggestions.value = filtered.slice(0, 5) // 最多显示5个建议
  showSuggestions.value = filtered.length > 0
}

// 选择建议
const selectSuggestion = (suggestion: AddressSuggestion) => {
  addressInput.value = suggestion.full
  selectedAddress.value = suggestion.full
  emit('update:modelValue', suggestion.full)
  showSuggestions.value = false
}

// 清除地址
const clearAddress = () => {
  addressInput.value = ''
  selectedAddress.value = ''
  suggestions.value = []
  showSuggestions.value = false
  emit('update:modelValue', '')
}

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== selectedAddress.value) {
    addressInput.value = newValue || ''
    selectedAddress.value = newValue || ''
  }
})

// 点击外部关闭建议
const handleClickOutside = (event: Event) => {
  const target = event.target as HTMLElement
  if (!target.closest(`#${inputId}`)?.parentElement?.contains(target)) {
    showSuggestions.value = false
  }
}

// 移除了重复的输入监听，现在通过handleAddressInput处理

// 添加全局点击监听
nextTick(() => {
  document.addEventListener('click', handleClickOutside)
})

// 组件卸载时移除监听
import { onUnmounted } from 'vue'
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
/* 确保建议列表在其他元素之上 */
.relative {
  position: relative;
}
</style>
